package com.joe.codemother.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.joe.codemother.entity.ChatHistory;
import com.joe.codemother.mapper.ChatHistoryMapper;
import com.joe.codemother.service.ChatHistoryService;
import org.springframework.stereotype.Service;
import com.joe.codemother.entity.enums.MessageTypeEnum;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.paginate.Page;

/**
 * 对话历史 服务层实现。
 *
 * @author joe
 */
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory>  implements ChatHistoryService{

	@Override
	public boolean saveUserMessage(Long appId, Long userId, String message) {
		ChatHistory history = ChatHistory.builder()
				.appId(appId)
				.userId(userId)
				.message(message)
				.messageType(MessageTypeEnum.USER.getValue())
				.build();
		return this.save(history);
	}

	@Override
	public boolean saveAiMessage(Long appId, Long userId, String message) {
		ChatHistory history = ChatHistory.builder()
				.appId(appId)
				.userId(userId)
				.message(message)
				.messageType(MessageTypeEnum.AI.getValue())
				.build();
		return this.save(history);
	}

	@Override
	public boolean saveError(Long appId, Long userId, String errorMessage) {
		ChatHistory history = ChatHistory.builder()
				.appId(appId)
				.userId(userId)
				.message(errorMessage)
				.messageType(MessageTypeEnum.ERROR.getValue())
				.build();
		return this.save(history);
	}

	@Override
	public QueryWrapper buildUserAppQueryWrapper(Long appId, Long userId) {
		return QueryWrapper.create()
				.eq("appId", appId)
				.eq("userId", userId);
	}

	@Override
	public Page<ChatHistory> pageAdmin(int pageNum, int pageSize, Long appId, Long userId) {
		QueryWrapper wrapper = QueryWrapper.create()
				.eq("appId", appId)
				.eq("userId", userId)
				.orderBy("createTime", false);
		return this.page(Page.of(pageNum, pageSize), wrapper);
	}
}
